﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZLCMS.Business;
using NHibernate;
using NHibernate.Criterion;
using ZLCMS.Business.DwzFrame;
using ZLCMS.Business.Util;
using ZLCMS.Business.TranferParam;
using System.Text;
using Newtonsoft.Json;
using ZLCMS.Data.Model;
using DotNet.Common.TransferParam;

namespace ZLCMS.Web.SystemManage.Basics.Param
{
    public partial class List : System.Web.UI.Page
    {
        protected FrameHelper _framePage;
        
        protected List<ParamGroupExp> _expGroupList;

        protected SysParam _groupDb;

        public string _groupId;

        protected void Page_Load(object sender, EventArgs e)
        {
            //初始化全局变量值
            _groupId = Request["gid"] == null ? null : Request["gid"];

            //初始化控件值
            ParamKit.Bind("TranferParam", ddl_groupcode, null, new List<ListItem>() { ParamKit.ParamItemEx_QXZ() }, new List<string>() { "TranferParam" }, "-1", "-1");
            ddl_groupcode.SelectedValue = _groupId;

            //初始化DWZ分页控件
            _framePage = new FrameHelper(this) { RecordCount = GetListCount() };

            LoadParamGroup();
            
            if (_framePage.IsAjaxPagerPostBack)
            {
                //分页返回
                BindList(_framePage.PageIndex, _framePage.PageSize);
            }
            else
            {
                //第一次进入页面
                BindList(1, _framePage.PageSize);
            }
        }

        protected void Query_Click(object sender, EventArgs e)
        {
            Server.Transfer("/SystemManage/Basics/Param/List.aspx?gid=" + ddl_groupcode.SelectedValue);
        }

        private void LoadParamGroup()
        {
            if ("-1" == ddl_groupcode.Text)
            {
                _groupDb = null;
                _expGroupList = null;

                return;
            }

            using (ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
            {
                _groupDb = session.CreateCriteria<SysParam>().Add(Expression.Eq("GroupCode", "TranferParam")).Add(Expression.Eq("ItemCode", ddl_groupcode.Text)).UniqueResult<SysParam>();

                _expGroupList = JsonConvert.DeserializeObject<List<ParamGroupExp>>(_groupDb.Param5 == null ? "" : _groupDb.Param5);

                rp_expname.DataSource = _expGroupList;
                rp_expname.DataBind();
            }
        }

        protected string GetExpParamItemHtml(object param5)
        {
            //参数组无扩展
            if (_expGroupList == null)
            {
                return null;
            }

            bool isMatch;
            String htmlMoudle = "<td>{0}</td>";
            StringBuilder htmlStr = new StringBuilder();

            List<ParamItemExp> expItemList = null;
            if (param5 != null)
            {
                //可能没有配置扩展
                expItemList = JsonConvert.DeserializeObject<List<ParamItemExp>>(param5.ToString());
            }

            //由于JSON没有顺序，这里需要通过比较找到对应的扩展
            foreach (ParamGroupExp groupExp in _expGroupList)
            {
                isMatch = false;

                if (expItemList != null)
                {
                    foreach (ParamItemExp itemExp in expItemList)
                    {
                        if (itemExp.Code == groupExp.Code)
                        {
                            isMatch = true;

                            if (groupExp.Type == ParamGroupExpType.String || groupExp.Type == ParamGroupExpType.Integer || groupExp.Type == ParamGroupExpType.Float)
                            {
                                htmlStr.AppendFormat(htmlMoudle, itemExp.Value);
                            }
                            else if (groupExp.Type == ParamGroupExpType.ParamCombo || groupExp.Type == ParamGroupExpType.ParamList)
                            {
                                //该参数组扩展有关联的参数组代码，需要翻译
                                if (!string.IsNullOrEmpty(groupExp.Relation.Trim()))
                                {
                                    htmlStr.AppendFormat(htmlMoudle, ParamKit.GetValue(groupExp.Relation, itemExp.Value, "&nbsp;"));
                                }
                                else
                                {
                                    htmlStr.AppendFormat(htmlMoudle, itemExp.Value);
                                }
                            }
                            else
                            {
                                htmlStr.AppendFormat(htmlMoudle, itemExp.Value);
                            }
                            break;
                        }
                    }
                }
                if (!isMatch)
                {
                    htmlStr.AppendFormat(htmlMoudle, "&nbsp;");
                }
            }

            return htmlStr.ToString();
        }

        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="pageIndex">分页索引</param>
        /// <param name="pageSize">分页大小</param>
        protected void BindList(int pageIndex, int pageSize)
        {
            using (ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
            {
                ICriteria criteria = session.CreateCriteria<SysParam>();
                SetupCondition(ref criteria);
                criteria.SetFirstResult((pageIndex - 1) * pageSize).SetMaxResults(pageSize);

                grid.DataSource = criteria.List();
                grid.DataBind();
            }
        }

        protected int GetListCount()
        {
            using (ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
            {
                ICriteria criteria = session.CreateCriteria<SysParam>();
                SetupCondition(ref criteria);
                return (int)criteria.SetProjection(Projections.RowCount()).UniqueResult();
            }
        }

        /// <summary>
        /// 设置查询条件
        /// </summary>
        /// <param name="crt"></param>
        protected void SetupCondition(ref ICriteria crt)
        {
            crt.Add(Expression.Eq("GroupCode", ddl_groupcode.SelectedValue));
        }
    }
}
